const http = require("http");
const path = require("path");
const express = require("express");
const socketIo = require("socket.io");
const app = express();
const httpServer = http.createServer(app);
// 将socketIo提供的id作为属性名，值即是登陆的名字
const userList = {}
const io = socketIo(httpServer);
io.on("connection", function (socket) {
    console.log("连接成功！", socket.id)
    socket.on("intoRoom", function (userName) {
        userList[socket.id] = userName;
        io.emit("onlineNum",Object.keys(userList).length,userList[socket.id]+"进入了房间\n");
    })
    socket.on("say",function(msg){
        io.emit("sayRoom",userList[socket.id],msg);
    })
    socket.on("disconnect",function(){
        const userName =  userList[socket.id];
        delete userList[socket.id];
        io.emit("onlineNum",Object.keys(userList).length,userName+"离开了房间\n");
    })
})
app.use(express.static(path.resolve(__dirname, "../html")));
// 登陆
app.get("/login", (req, res) => {
    // /login?userName=xxxx
    const {userName} = req.query;
    const values = Object.values(userList);
    if (values.includes(userName)) {
        // 名字已经存在
        res.json({
            ok: -1
        })
    } else {
        // 名字不存在
        res.json({
            ok: 1
        })
    }

})
httpServer.listen(80, function () {
    console.log("success");
})